﻿

public class NetHandler_AddComment : GameServerMessageHandler
{
    public const string Key = "AddComment";

    public static NetHandler_AddComment NewHandler()
    {
        return new NetHandler_AddComment();
    }

    protected override ISerialize NewData() => new AddCommentRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        AddCommentRequestData requestData = _data as AddCommentRequestData;

        GameDebug.Log($"用户{client.userID}  添加评论:{requestData?.momentUserId} {requestData?.momentId}");

        UserServer user = Game.instance.GetUser(client.userID);

        AddCommentResponseData response = new AddCommentResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if (requestData != null)
            {
                long deviceId = user.data.id;
                long time = (long)CommonFunctions.GetTimeStampSeconds();

                long commentId = comments.AddComment(requestData.momentUserId, requestData.momentId, deviceId, time,
                    requestData.content, "" );

                UserInfo commentUserInfo = UserServer.GetUserInfoWithUserId(deviceId);
                if (commentUserInfo != null)
                {
                    var miniUserInfo = new MiniUserInfo(commentUserInfo);
                    Comment comment = new Comment(commentId, requestData.momentUserId, commentId, miniUserInfo, requestData.content, null, time, null);

                    //TODO. 发送事件

                    moments momentTable = UserServer.FindInMomentTable(requestData.momentUserId, requestData.momentId);
                    if (momentTable != null)
                    {
                        List<long> comments = users.String2LongList(momentTable.comments);
                        comments.Add(commentId);

                        moments.UpdateComments(requestData.momentUserId, requestData.momentId, comments);
                    }
                    else
                    {
                        GameDebug.LogError($"cant find moment, momentUserId:{requestData.momentUserId}  momentId:{requestData.momentId}");
                    }

                    response.comment = comment;

                    response.code = 0;
                }
                else
                {
                    response.code = ErrorCode.UserNotFound;
                    GameDebug.LogError($"cannot find userinfo with deviceId:{deviceId}");
                }
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data != null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
